package com.dinzeer.godfox.entity;

import mods.flammpfeil.slashblade.SlashBladeConfig;
import mods.flammpfeil.slashblade.ability.StunManager;
import mods.flammpfeil.slashblade.capability.concentrationrank.ConcentrationRankCapabilityProvider;
import mods.flammpfeil.slashblade.capability.concentrationrank.IConcentrationRank;
import mods.flammpfeil.slashblade.entity.EntityDrive;
import mods.flammpfeil.slashblade.entity.Projectile;
import mods.flammpfeil.slashblade.item.ItemSlashBlade;
import mods.flammpfeil.slashblade.util.AttackManager;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraftforge.entity.PartEntity;

import java.util.Optional;

public class GoldenDrive extends EntityDrive {

    // 伤害计算参数
    private static final float BASE_DAMAGE_MULTIPLIER = 1.0f;
    private static final float HEALTH_DAMAGE_RATIO = 1.0f;
    private static final float RANK_BONUS_BASE = 0.5f;
    private static final float CRITICAL_DAMAGE_RANGE = 0.5f;
    private static final int FIRE_DURATION = 5;

    public GoldenDrive(EntityType<? extends Projectile> entityTypeIn, Level worldIn) {
        super(entityTypeIn, worldIn);
    }

    @Override
    protected void onHitEntity(EntityHitResult entityHitResult) {
        Entity target = entityHitResult.getEntity();
        Entity shooter = this.getShooter();

        DamageSource damageSource = createDamageSource(shooter);
        float finalDamage = calculateFinalDamage(shooter, target);

        if (attemptDamageTarget(target, damageSource, finalDamage, shooter)) {
            applyPostDamageEffects(target, shooter);
        }
    }

    /**
     * 创建伤害来源
     */
    private DamageSource createDamageSource(Entity shooter) {
        if (shooter == null) {
            return this.damageSources().indirectMagic(this, this);
        }
        return this.damageSources().indirectMagic(this, shooter);
    }

    /**
     * 计算最终伤害值 - 新的直观伤害算法
     */
    private float calculateFinalDamage(Entity shooter, Entity target) {
        float baseDamage = (float) this.getDamage();

        if (!(shooter instanceof LivingEntity livingShooter)) {
            return baseDamage;
        }

        // 1. 基础伤害乘以生命值比例
        float healthBasedDamage = baseDamage * livingShooter.getMaxHealth() * HEALTH_DAMAGE_RATIO;

        // 2. 玩家专属加成
        float playerBonus = calculatePlayerBonusDamage(livingShooter);

        // 3. 武器和全局加成
        float weaponMultiplier = (float) (AttackManager.getSlashBladeDamageScale(livingShooter)
                * SlashBladeConfig.SLASHBLADE_DAMAGE_MULTIPLIER.get());

        // 4. 组合基础伤害
        float totalDamage = (healthBasedDamage + playerBonus) * weaponMultiplier * BASE_DAMAGE_MULTIPLIER;

        // 5. 暴击加成
        if (this.getIsCritical()) {
            totalDamage = applyCriticalStrike(totalDamage);
        }

        return Math.max(1.0f, totalDamage); // 确保最小伤害为1
    }

    /**
     * 计算玩家专属伤害加成
     */
    private float calculatePlayerBonusDamage(LivingEntity shooter) {
        if (!(shooter instanceof Player player)) {
            return 0.0f;
        }

        // 获取集中等级
        Optional<IConcentrationRank.ConcentrationRanks> rankOpt = player
                .getCapability(ConcentrationRankCapabilityProvider.RANK_POINT)
                .map(rp -> rp.getRank(player.getCommandSenderWorld().getGameTime()));

        if (rankOpt.isEmpty()) {
            return 0.0f;
        }

        IConcentrationRank.ConcentrationRanks rank = rankOpt.get();
        float rankBonus = rank.level * RANK_BONUS_BASE;

        // S级及以上等级的额外加成
        if (rank.level >= IConcentrationRank.ConcentrationRanks.S.level) {
            rankBonus = calculateHighRankBonus(player, rankBonus);
        }

        return rankBonus;
    }

    /**
     * 计算高等级（S级及以上）的额外加成
     */
    private float calculateHighRankBonus(Player player, float baseRankBonus) {
        // 获取武器精炼等级
        Optional<Integer> refineOpt = player.getMainHandItem()
                .getCapability(ItemSlashBlade.BLADESTATE)
                .map(state -> state.getRefine());

        int refineLevel = refineOpt.orElse(0);
        int playerLevel = player.experienceLevel;

        // 取玩家等级和精炼等级的较小值作为加成基础
        int bonusBase = Math.min(playerLevel, refineLevel);
        float refinedBonus = (float) (bonusBase * SlashBladeConfig.REFINE_DAMAGE_MULTIPLIER.get());

        // 返回基础等级加成和精炼加成的较大值
        return Math.max(baseRankBonus, refinedBonus);
    }

    /**
     * 应用暴击效果
     */
    private float applyCriticalStrike(float baseDamage) {
        int maxBonus = Mth.ceil(baseDamage * CRITICAL_DAMAGE_RANGE) + 2;
        return baseDamage + this.random.nextInt(maxBonus);
    }

    /**
     * 尝试对目标造成伤害
     */
    private boolean attemptDamageTarget(Entity target, DamageSource damageSource, float damage, Entity shooter) {
        if (!(target instanceof LivingEntity)) {
            return false;
        }


        int originalFireTime = target.getRemainingFireTicks();


        if (this.isOnFire() && !(target instanceof EnderMan)) {
            target.setSecondsOnFire(FIRE_DURATION);
        }

        // 重置无敌时间并尝试造成伤害
        target.invulnerableTime = 0;

        if (target.hurt(damageSource, damage)) {
            updateLastHurtMob(target, shooter);
            return true;
        } else {

            target.setRemainingFireTicks(originalFireTime);
            return false;
        }
    }

    /**
     * 更新攻击者的最后攻击目标
     */
    private void updateLastHurtMob(Entity target, Entity shooter) {
        if (shooter instanceof LivingEntity livingShooter) {
            Entity actualTarget = target instanceof PartEntity ? ((PartEntity<?>) target).getParent() : target;
            livingShooter.setLastHurtMob(actualTarget);
        }
    }

    /**
     * 应用伤害后的效果
     */
    private void applyPostDamageEffects(Entity target, Entity shooter) {
        Entity actualTarget = target instanceof PartEntity ? ((PartEntity<?>) target).getParent() : target;

        if (actualTarget instanceof LivingEntity livingTarget) {
            // 应用击晕效果
            StunManager.setStun(livingTarget);

            // 应用附魔效果
            if (!this.level().isClientSide() && shooter instanceof LivingEntity) {
                EnchantmentHelper.doPostHurtEffects(livingTarget, shooter);
                EnchantmentHelper.doPostDamageEffects((LivingEntity) shooter, livingTarget);
            }

            // 应用药水效果
            this.affectEntity(livingTarget, this.getPotionEffects(), 1.0);

            // 播放音效
            playHitSounds(livingTarget, shooter);
        }

        this.playSound(this.getHitEntitySound(), 1.0F, 1.2F / (this.random.nextFloat() * 0.2F + 0.9F));
    }

    /**
     * 播放命中音效
     */
    private void playHitSounds(LivingEntity target, Entity shooter) {
        if (shooter != null && target != shooter && target instanceof Player && shooter instanceof ServerPlayer) {
            ((ServerPlayer) shooter).playNotifySound(
                    this.getHitEntityPlayerSound(),
                    SoundSource.PLAYERS,
                    0.18F,
                    0.45F
            );
        }
    }
}